/**
 * 
 */
package com.hfjyz.examination.service.impl;

import java.util.Collections;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;

import com.hfjyz.examination.command.LoginCommand;
import com.hfjyz.examination.dao.UserDao;
import com.hfjyz.examination.domain.UserInfo;
import com.hfjyz.examination.object.LoginInfo;
import com.hfjyz.examination.service.LoginService;
import com.hfjyz.examination.util.CryptUtil;

/**
 *
 */
public class LoginServiceImpl implements LoginService {
	private UserDao userDao;

	@Override
	public LoginInfo login(HttpServletRequest request,
			HttpServletResponse response, LoginCommand command,
			BindException errors) throws Exception {
		LoginInfo l = null;
		if (command.isAdmin()) {
			UserInfo u = userDao.getByUsername(command.getUsername());
			if (u == null || !command.getPassword().equals(u.getUserpass())) {
				errors.reject("error.login",
						"failed login! confirm your username or password.");
				return null;
			}
			l = new LoginInfo();
			l.setId(u.getId());
			l.setRoles(Collections.singleton(LoginInfo.ROLE_ADMIN));
		} else {
			UserInfo u = userDao.getByUsername(command.getUsername());
			if (u == null
					|| !CryptUtil.encrypt(command.getPassword()).equals(
							u.getUserpass())) {
				errors.reject("error.login",
						"failed login! confirm your username or password.");
				return null;
			}
			l = new LoginInfo();
			l.setId(u.getId());
		}
		return l;
	}

	/**
	 * @return the userDao
	 */
	public UserDao getUserDao() {
		return userDao;
	}

	/**
	 * @param userDao
	 *            the userDao to set
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
